package com.dingup.provider.controller.sys;

import com.alibaba.fastjson.JSON;
import com.dingup.api.Util.JwtTokenUtil;
import com.dingup.api.Util.RedisUtils;
import com.dingup.api.base.HttpResContent;
import com.dingup.api.enums.DataPermissionEnum;
import com.dingup.api.model.sys.SysPermissionGroup;
import com.dingup.api.model.sys.SysRole;
import com.dingup.provider.mapper.SysPermissionGroupRoleMapper;
import com.dingup.provider.mapper.SysRoleMapper;
import com.dingup.provider.mapper.SysUserMapper;
import com.dingup.provider.model.sys.UpdateRolePermission;
import com.dingup.provider.service.log.RoleUpdateLogService;
import com.dingup.provider.service.sys.SysPermissionService;
import com.suyeer.basic.util.BHttpResUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.dingup.api.base.BaseUtil.saveErrorMsgAndData;
import static com.dingup.api.base.BaseUtil.saveSuccessMsgAndData;

/**
 * Created by wancheng on 2018/7/16.
 */
@RestController
@RequestMapping("/permission")
public class SysPermissionController {

    private final Logger logger = LoggerFactory.getLogger(SysPermissionController.class);

    @Autowired
    SysRoleMapper sysRoleMapper;
    @Autowired
    SysPermissionService sysPermissionService;
    @Autowired
    SysPermissionGroupRoleMapper sysPermissionGroupRoleMapper;
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    RoleUpdateLogService roleUpdateLogService;


    @RequestMapping(value = "/get_user_permission.do",method = RequestMethod.POST)
    public void getUserPermission(HttpServletRequest request,
                    HttpServletResponse response) {

        HttpResContent<Map<String,Boolean>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取用户的权限列表");
        try {
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            String userId = RedisUtils.getInstance().getUserId(userAccount);
            Map<String,Boolean> res = sysPermissionService.getRoleHasPermissionGroupTreeByUserId(userId);
            saveSuccessMsgAndData(hrc, res);
        } catch (Exception e) {
            e.printStackTrace();
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/get_role_permission.do",method = RequestMethod.POST)
    public void get(HttpServletRequest request,
                       HttpServletResponse response,
                       Integer roleId) {

        HttpResContent<Map<String,Object>> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("获取身份的权限列表");
        try {
            String userAccount = JwtTokenUtil.getUserAccountFromRequset(request);
            String userId = RedisUtils.getInstance().getUserId(userAccount);
            SysRole role = sysRoleMapper.selectByPrimaryKey(roleId);
            List<SysPermissionGroup> res = sysPermissionService.getRoleHasPermissionGroupTreeByRoleIdAndUserId(roleId,userId);
            Map<String,Object> map = new HashMap();
            Map<String,Object> dataPermissionMap = new HashMap();
            dataPermissionMap.put("dataPermission",role.getDataPermission());
            if(role.getCreateUserId() == null){
                dataPermissionMap.put("status",false);
            }else{
                dataPermissionMap.put("status",true);
            }
            map.put("dataPermission",dataPermissionMap);
            map.put("resourcePermission",res);
            saveSuccessMsgAndData(hrc, map);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }

    @RequestMapping(value = "/update_role_permission.do",method = RequestMethod.POST)
    public void update(HttpServletRequest request,
                       HttpServletResponse response,
                       Integer roleId,String permissionGroup) {

        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("修改身份权限");
        try {
            String userId = RedisUtils.getInstance().getUserId(request);
            List<UpdateRolePermission> list = JSON.parseArray(permissionGroup,UpdateRolePermission.class);
            sysPermissionService.updateRolePermission(roleId,list);
            //身份全系修改记录
            roleUpdateLogService.updateRoleLog(roleId,userId,permissionGroup);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }
    @RequestMapping(value = "/update_role_dataPermission.do",method = RequestMethod.POST)
    public void updateRoleDataPermission(HttpServletRequest request,
                       HttpServletResponse response,
                       Integer roleId,Integer dataPermission) {

        HttpResContent<Boolean> hrc = new HttpResContent<>(request, response);
        hrc.setFuncDes("修改身份数据权限");
        try {
            if(DataPermissionEnum.getEnum(dataPermission) == null){
                throw new Exception("dataPermission参数不合法");
            }
            SysRole role = sysRoleMapper.selectByPrimaryKey(roleId);
            role.setDataPermission(dataPermission);
            sysRoleMapper.updateByPrimaryKeySelective(role);
            saveSuccessMsgAndData(hrc, true);
        } catch (Exception e) {
            saveErrorMsgAndData(hrc, e);
        } finally {
            BHttpResUtil.writeResult(hrc, true);
        }
    }
}
